<?php


namespace app\admin\controller\auth;


use app\admin\controller\AController;
use app\admin\service\auth\AdminService;
use app\admin\service\RequestService;
use app\model\auth\Admin;
use app\model\auth\AdminGroupAccess;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;

class AdminController extends AController {

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function index(RequestService $requestService): \think\response\Json
    {
        $query = (new Admin)->with(['groups']);
        $list = $requestService->read($query)->each(function ($v){
            $v->groupTitle = getRelValue($v->groups[0], 'title');
        });

        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }

    public function add(Request $request, AdminService $adminService){
        if ($request->isPost()){
            try {
                $post = $request->post();
                $adminService->save($post,'add');
            } catch (\Exception $e) {
                return jsonError($e->getMessage());
            }
            return jsonSuccess();
        }
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function edit(Request $request, AdminService $adminService)
    {

        $id = $request->param('id');

        if(!$id){
            return jsonError(PARAM_ERROR);
        }
        if($request->isPost()){
            try {
                $post = $this->post();
                $adminService->save($post, 'edit');
            }catch (\Exception $e){
                return jsonError($e->getMessage());
            }

            return  jsonSuccess();

        }else{

            $info = $adminService->info($id);
            if(!$info){
                return jsonError(NOT_FOUND);
            }
            $info->group_id = getRelValue($info->groups[0],'id');

            return jsonSuccess([
                'info' => $info
            ]);
        }
    }


    public function del(){
        $ids = request()->param('ids');
        if (!$ids || count($ids)==0){
            return jsonError('请选择要删除的记录');
        }
        if (in_array('1', $ids)){
            return jsonError("不能删除【admin】");
        }
        Admin::where('id', 'in', $ids)->delete();
        AdminGroupAccess::where('uid', 'in', $ids)->delete();

        return jsonSuccess();
    }

}
